package com.zx._02_thread.线程池;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @version v1.0
 * @Project: knowledge
 * @Title: 单线程与多线程对比
 * @Description: 简单操作，多线程操作比单线程要慢的多。多线程是在处理复杂程序的时候，能体现优势
 *         test1 = 163495800
 *         test2 = 51181200
 *         test3 = 313946200  //存在线程上下文切换，影响较大
 * @author: zhangxue
 * @date: 2020年5月8日下午10:27:30
 * @company: 未知
 * @Copyright: Copyright (c) 2015
 */
public class 单线程与多线程性能对比 {

    private static final int arr_len = 10000;
    private static final int for_num = 100;

    public static void main(String[] args) {
        // 初始化数据
        String[] sarr = new String[arr_len];
        for (int i = 0; i < sarr.length; i++) {
            sarr[i] = String.valueOf(i);
        }

        test1(sarr);
        test2(sarr);
        test3(sarr);


    }

    public static void test1(String[] sarr) {
        long t1 = System.nanoTime();
        for (int i = 0; i < for_num; i++) {
            HashMap<String, String> map = new HashMap<>();
            for (String kv : sarr) {
                map.put(kv, kv);
            }
        }
        long t2 = System.nanoTime();
        System.out.println("test1 = " + (t2 - t1));
    }

    public static void test2(String[] sarr) {
        long t1 = System.nanoTime();
        for (int i = 0; i < for_num; i++) {
            HashMap<String, String> map = new HashMap<>(sarr.length);
            for (String kv : sarr) {
                map.put(kv, kv);
            }
        }
        long t2 = System.nanoTime();
        System.out.println("test2 = " + (t2 - t1));
    }

    public static void test3(String[] sarr) {
        // 热身一次
//		ExecutorService pool = Executors.newCachedThreadPool();
        ExecutorService pool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < for_num; i++) {
            Map<String, String> map = new HashMap<>(sarr.length);//暂时不考虑安全性
            for (String kv : sarr) {
                pool.execute(() -> {
                    map.put(kv, kv);
                });
            }
        }

        long t1 = System.nanoTime();
        for (int i = 0; i < for_num; i++) {
            Map<String, String> map = new ConcurrentHashMap<>(sarr.length);
            for (String kv : sarr) {
                pool.execute(() -> {
                    map.put(kv, kv);
                });
            }
        }
        long t2 = System.nanoTime();
        System.out.println("test3 = " + (t2 - t1));

        pool.shutdown();
    }

}
